package com.zx.deploy.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.zx.deploy.common.utils.FileUtil;
import com.zx.deploy.config.DeployConfig;
import com.zx.deploy.model.SpeedProgress;
import com.zx.deploy.service.DeployService;
import com.zx.deploy.service.SoftService;

/**
 * Created by IBM on 2018/4/3.
 */
@Service
public class DeployServiceImpl implements DeployService {

    @Resource
    private SoftService softService;

    /**
     * 环境变量
     */
    @Autowired
    protected DeployConfig config;

    @Override
    public SpeedProgress update() throws IOException {
		SpeedProgress speed = new SpeedProgress();
		new Thread(() -> softService.install(config, speed)).start();
        return speed;
    }

	@Override
	public Map<String, Object> getVersions() {
    	Map<String,Object> result = new HashMap<>();
		File currentVersionFile = FileUtil.getFile("current-version.txt");
		File oldVersionFile = FileUtil.getFile("old-version.txt");
		try {
			String currentVersionStr = FileUtils.readFileToString(currentVersionFile);
			String oldVersionStr = FileUtils.readFileToString(oldVersionFile);
			Object currentVersion = null;
			Object oldVersion = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
			if(StringUtils.isEmpty(currentVersionStr)){
				currentVersion = "无";
			}else{
                currentVersion = sdf.format(new Date(Long.parseLong(currentVersionStr)));
            }
			if(StringUtils.isEmpty(oldVersionStr)){
				oldVersion = "无";
			}else{
                oldVersion = sdf.format(new Date(Long.parseLong(oldVersionStr)));
            }
			result.put("currentVersion",currentVersion);
			result.put("oldVersion",oldVersion);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
